package cn.lut.springboot.handler;

import cn.lut.springboot.entity.Employee;
import cn.lut.springboot.util.ResultEntity;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @user:dell
 * @date:2021年01月05 17:26
 */
@RestController
public class EmployeeHandler {
    @RequestMapping("/provider/get/employee/remote")
    public Employee getEmployeeRemote() {
        return new Employee(555, "tom555-", 555.55);
    }
//    @RequestMapping("/provider/get/employee/remote")
//    public Employee getEmployeeRemote(HttpServletRequest request) {
//        // 获取当前 Web 应用的端口号
//        int serverPort = request.getServerPort();
//        return new Employee(555, "tom555-"+serverPort, 555.55);
//    }
    @RequestMapping("/provider/get/employee/by/id")
    public List<Employee> getEmpListRemote(@RequestParam("keyword") String keyword){
        List<Employee> empList=new ArrayList<>();
        System.out.println("keyword的值是"+keyword);
        empList.add(new Employee(33,"emp33",333.33));
        empList.add(new Employee(44,"emp44",444.44));
        empList.add(new Employee(55,"emp55",555.555));
        return empList;
    }
    // @HystrixCommand 注解通过 fallbackMethod 属性指定断路情况下要调用的备份方法
    @HystrixCommand(fallbackMethod = "getEmpWithCircuitBreakerBackUp")
    @RequestMapping("/provider/get/emp/with/circuit/breaker")
    public ResultEntity<Employee> getEmpWithCircuitBreaker(@RequestParam("signal") String signal) throws InterruptedException {
        if("quick-bang".equals(signal)) {
            throw new RuntimeException();
        }
        if("slow-bang".equals(signal)){
            Thread.sleep(5000);
        }
        return ResultEntity.successWithData(new Employee(666,"empName666",666.66));
    }
    public ResultEntity<Employee> getEmpWithCircuitBreakerBackUp(@RequestParam("signal") String signal){
        return ResultEntity.failed("circuit break workded,with signal="+signal);
    }
}
